# 项目名称
PROJECT := x-smi

# Go模块名称
MODULE := gpu-query

# 版本信息（可以从git标签获取）
VERSION ?= $(shell git describe --tags 2>/dev/null || echo "v0.0.0")
BUILD_TIME := $(shell date -u '+%Y-%m-%d_%H:%M:%S')
COMMIT_HASH := $(shell git rev-parse --short HEAD 2>/dev/null || echo "unknown")

# Go构建标志
LDFLAGS := -ldflags "-s -w -X main.version=$(VERSION) -X main.buildTime=$(BUILD_TIME) -X main.commitHash=$(COMMIT_HASH)"

# 目标平台
PLATFORMS := linux-amd64 linux-arm64

# 支持的GPU类型
GPU_TYPES := metax nvidia iluvatar ascend cambricon inspur hygon enflame kunlun br

# 默认构建当前平台
.DEFAULT_GOAL := build

# 构建当前平台
build:
	@echo "Building for current platform..."
	go build $(LDFLAGS) -o $(PROJECT) .

# 构建所有平台
build-all: $(PLATFORMS)

# 清理构建文件
clean:
	@echo "Cleaning build artifacts..."
	rm -f $(PROJECT) $(PROJECT)-*
	rm -rf dist/

# 安装到GOPATH/bin
install:
	go install $(LDFLAGS) .

# 运行测试
test:
	go test ./...

# 代码格式检查
fmt:
	go fmt ./...

# 显示支持的GPU类型
gpu-types:
	@echo "Supported GPU types:"
	@for type in $(GPU_TYPES); do \
		echo "  $$type"; \
	done

# 为每个平台定义构建规则
define build-platform
$(1):
	@echo "Building for $(1)..."
	GOOS=$(word 1,$(subst -, ,$(1))) GOARCH=$(word 2,$(subst -, ,$(1))) go build $(LDFLAGS) -o $(PROJECT)-$(1) .
endef

# 应用构建规则到所有平台
$(foreach platform,$(PLATFORMS),$(eval $(call build-platform,$(platform))))

# 创建发布包
release: build-all
	@echo "Creating release packages..."
	@mkdir -p dist/
	@for platform in $(PLATFORMS); do \
		dir=dist/$(PROJECT)-$(VERSION)-$$platform; \
		mkdir -p $$dir; \
		cp $(PROJECT)-$$platform $$dir/$(PROJECT); \
		cp LICENSE README.md $$dir/; \
		tar -czf $$dir.tar.gz -C dist/ $(PROJECT)-$(VERSION)-$$platform; \
		zip -qr $$dir.zip $$dir; \
	done
	@echo "Release packages created in dist/"

# 显示帮助信息
help:
	@echo "Available targets:"
	@echo "  build       - Build for current platform (default)"
	@echo "  build-all   - Build for all platforms: $(PLATFORMS)"
	@echo "  clean       - Remove build artifacts"
	@echo "  install     - Install to GOPATH/bin"
	@echo "  test        - Run tests"
	@echo "  fmt         - Format code"
	@echo "  gpu-types   - Show supported GPU types"
	@echo "  release     - Create release packages for all platforms"
	@echo "  help        - Show this help message"

.PHONY: build build-all clean install test fmt gpu-types release help